<template>
  <div class="wrapper">

    <!-- header部分 -->
    <header>
      <i class="fa fa-angle-left" @click="goback"></i>
      <p>确认订单</p>
    </header>

    <!-- 订单信息部分 -->
    <div class="order-info">
      <h5>订单配送至：</h5>
      <div class="order-info-address" @click="toUserAddress">
        <p>{{deliveryaddress!=null?deliveryaddress.address:'请选择收货地址'}}</p>
        <i class="fa fa-angle-right"></i>
      </div>
      <p>{{deliveryaddress!=null?deliveryaddress.contactName:user.userName}}{{deliveryaddress!=null?deliveryaddress.contactSex:user.userSex | sexFilter}} {{deliveryaddress!=null?deliveryaddress.contactTel:user.userId}}</p>
    </div>

    <h3>{{business.businessName}}</h3>

    <!-- 订单明细部分 -->
    <ul class="order-detailed">
      <li v-for="cartItem in cartArr" :key="cartItem.cartId">

        <div class="order-detailed-left">
       <!--   <p>Food ID: {{ cartItem.foodId }}</p>  -->
         <!--<img :src="item.foodImg">-->
          <img :src="getFoodImg(cartItem.foodId)" alt="no">
          <p>{{getFoodName(cartItem.foodId)}}</p>
          <p>数量: {{cartItem.quantity}}</p>

        </div>
        <!--<p>&#165;{{(item.foodPrice*item.quantity).toFixed(2)}}</p>-->
        <p>总价格: {{ (getFoodPrice(cartItem.foodId) * cartItem.quantity).toFixed(2)}}</p>
      </li>

    </ul>
    <div class="order-deliveryfee">
      <p>配送费</p>
      <p>&#165;{{this.business.deliveryPrice}}</p>
    </div>


    <!-- 订单合计部分 -->
    <div class="total">
      <div class="total-left">

        &#165;{{calculateTotalPriceAll.toFixed(2)}}


      </div>
      <div class="total-right" @click="toPayment">
        去支付
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Orders',
  data() {
    return {
      businessId: this.$route.query.businessId,
      business: {},
      user: {},
      cartArr: [],
      foodArr:[],
      foodArrObject:{},
      deliveryaddress:{},
      foodImgs:{},// 用于存储foodId和对应foodImg的映射关系
      foodNames:{},
    }
  },
  created() {
    this.user = this.$getSessionStorage('user');
    this.deliveryaddress = this.$getLocalStorage(this.user.userId);

    //查询当前商家
    let url1 = `BusinessController/getBusinessById/${this.businessId}`;
    this.$axios.get(url1).then(response => {
      this.business = response.data.result;
    }).catch(error => {
      console.error(error);
    });
    //查询当前用户在购物车中的当前商家食品列表
    let url2 = `CartController/listCart/${this.user.userId}/${this.businessId}`;
    this.$axios.get(url2,{
      headers : {
        'token': sessionStorage.getItem('token')
      }
    }).then(response => {
      this.cartArr = response.data.result;
    }).catch(error => {
      console.error(error);
    });



      let url3 = `FoodController/listFoodByBusinessId/${this.businessId}`;
      this.$axios.get(url3).then(response => {
        this.foodArr=response.data.result;
      }).catch(error => {
        console.error(error);
      });




  },



  computed: {

    /*totalPrice() {
      let totalPrice = 0.00;
      for (let cartItem of this.cartArr) {

        let url3 = `FoodController/listFoodByFoodId/${cartItem.foodId}`;
        this.$axios.get(url3).then(response => {
          this.foodItem = response.data.result; // 使用 push 方法将食物对象添加到数组中
        }).catch(error => {
          console.error(error);
        });

        let subTotalPrice= this.foodItem.foodPrice * cartItem.quantity;
        totalPrice += Number(subTotalPrice.toFixed(2)); // 将每次计算结果保留两位小数并累加到总价
      }

      totalPrice +=  parseFloat(this.business.deliveryPrice.toFixed(2));
      return totalPrice.toFixed(2);
    },


     */
    calculateTotalPrice() {
      let totalPrice = 0.00;
      this.cartArr.forEach(item => {
        const foodPrice = this.getFoodPrice(item.foodId);
        totalPrice += foodPrice * item.quantity;
      });
      return totalPrice.toFixed(2);
    },
    calculateTotalPriceAll(){
      let totalPrice = 0.00;
      this.cartArr.forEach(item => {
        const foodPrice = this.getFoodPrice(item.foodId);
        totalPrice += foodPrice * item.quantity;
      });
      let url1 = `BusinessController/getBusinessById/${this.businessId}`;
      this.$axios.get(url1).then(response => {
        this.business = response.data.result;
      }).catch(error => {
        console.error(error);
      });
      return totalPrice + this.business.deliveryPrice;
    }




  },



  filters:{
    sexFilter(value){
      return value==1?"先生":"女士";
    }
  },
  methods:{
    goback() {
      this.$router.go(-1);
    },
    toUserAddress(){
      this.$router.push({path:'/userAddress',query:{businessId:this.businessId}})
    },

    getFoodPrice(foodId) {

      const food = this.foodArr.find(item => item.foodId === foodId);
      return food ? food.foodPrice : 0;
    },
    getTotalPrice(foodId, quantity) {
      const foodPrice = this.getFoodPrice(foodId);
      return foodPrice * quantity;
    },

    getFoodImg(foodId) {
      // 在foodArr中查找具有相同foodId的食品项
      const foodItem = this.foodArr.find(item => item.foodId === foodId);
      // 如果找到了对应的食品项，则将其foodImg添加到foodImgs中，并返回foodImg
      if (foodItem) {
        this.foodImgs[foodId] = foodItem.foodImg;
        return foodItem.foodImg;
      }
    },

    getFoodName(foodId) {
      const foodItem = this.foodArr.find(item => item.foodId === foodId);
      // 如果找到了对应的食品项，则将其foodImg添加到foodName中，并返回foodName
      if (foodItem) {
        this.foodNames[foodId] = foodItem.foodName;
        return foodItem.foodName;
      }
    },



    toPayment(){
      if(this.deliveryaddress==null){
        alert('请选择送货地址!');
        return;
      }


      //创建订单
      let url = `OrdersController/createOrders/${this.user.userId}/${this.businessId}/${this.deliveryaddress.daId}/${this.calculateTotalPrice}`;

      this.$axios.post(url).then(response => {
        let orderId = response.data.result;
        if(orderId>0){
          this.$router.push({path:'/payment',query:{orderId:orderId}});
          console.log(orderId);
        }else{
         // alert('创建订单失败!');
        }
      }).catch(error => {
        console.error(error);
      });
    }

  }
}
</script>

<style scoped>
/********** 总容器 **********/
.wrapper {
  width: 100%;
  height: 100%;
}

/********** header **********/
.wrapper header {
  width: 100%;
  height: 12vw;
  background: linear-gradient(#F37373, #F08080, #EF9292);
  color: #fff;
  font-size: 4.8vw;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 1000;
  display: flex;
  align-items: center;

}

.wrapper header i {
  margin-left: 6vw;
}

.wrapper header p {
  margin-left: 33vw;
}

/********** 订单信息部分 **********/
.wrapper .order-info {
  width: 100%;
  margin-top: 12vw;
  background:linear-gradient(#EF9292,#F08080,#F37373);
  box-sizing: border-box;
  padding: 2vw;
  color: #fff;
}

.wrapper .order-info h5 {
  font-size: 3vw;
  font-weight: 300;
}

.wrapper .order-info .order-info-address {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;

  font-weight: 700;
  user-select: none;
  cursor: pointer;
  margin: 1vw 0;
}

.wrapper .order-info .order-info-address p {
  width: 90%;
  font-size: 5vw;
}

.wrapper .order-info .order-info-address i {
  font-size: 6vw;
}

.wrapper .order-info p {
  font-size: 3vw;
}

.wrapper h3 {
  box-sizing: border-box;
  padding: 3vw;
  font-size: 4vw;
  color: #666;
  border-bottom: solid 1px #DDD;
}

/********** 订单明细部分 **********/
.wrapper .order-detailed {
  width: 100%;
}

.wrapper .order-detailed li {
  width: 100%;
  height: 16vw;
  box-sizing: border-box;
  padding: 3vw;
  color: #666;

  display: flex;
  justify-content: space-between;
  align-items: center;
}

.wrapper .order-detailed li .order-detailed-left {
  display: flex;
  align-items: center;
}

.wrapper .order-detailed li .order-detailed-left img {
  width: 10vw;
  height: 10vw;
}

.wrapper .order-detailed li .order-detailed-left p {
  font-size: 3.5vw;
  margin-left: 3vw;
}

.wrapper .order-detailed li p {
  font-size: 3.5vw;
}

.wrapper .order-deliveryfee {
  width: 100%;
  height: 16vw;
  box-sizing: border-box;
  padding: 3vw;
  color: #666;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 3.5vw;
}

/********** 订单合计部分 **********/
.wrapper .total {
  width: 100%;
  height: 14vw;

  position: fixed;
  left: 0;
  bottom: 0;

  display: flex;
}

.wrapper .total .total-left {
  flex: 2;
  background-color: #505051;
  color: #fff;
  font-sizi: 4.5vw;
  font-weight: 700;
  user-select: none;

  display: flex;
  justify-content: center;
  align-items: center;
}

.wrapper .total .total-right {
  flex: 1;
  background-color: #EF9292;
  color: #fff;
  font-size: 4.5vw;
  font-weight: 700;
  user-select: none;
  cursor: pointer;

  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
